package com.lfg.leetcode.leetcode0;


import java.util.Arrays;

public class No16ThreeSumClosest {
    public static int threeSumClosest(int[] nums, int target) {
        if (nums.length < 3) {
            return 0;
        }
        Arrays.sort(nums);
        int closest = Integer.MAX_VALUE;
        int ret = 0;
        for (int i = 1; i < nums.length; i++) {
            int n = i - 1;
            int m = i + 1;
            while (n >= 0 && m < nums.length) {
                int sum = nums[i] + nums[n] + nums[m];
                int diff = target - sum;
                if (diff == 0) {
                    return sum;
                }
                if (Math.abs(diff) < closest) {
                    ret = sum;
                    closest = Math.abs(diff);
                }
                if (sum > target) {
                    n--;
                } else {
                    m++;
                }
            }
        }
        return ret;
    }


    public static void main(String[] args) {
        System.out.println(threeSumClosest(new int[]{0, 2, 1, -3}, 1));
//        System.out.println(threeSum(new int[]{-1,0,1,2,-1,-4}));
//        System.out.println(threeSum(new int[]{-2,0,0,2,2}));
    }
}
